package com.lhy.backend.components.filter;


import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.lhy.backend.components.utils.JwtUtils;
import com.lhy.backend.domain.entity.user.SysRole;
import com.lhy.backend.domain.entity.user.SysUser;
import io.jsonwebtoken.Claims;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;


@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    @Autowired
    private JwtUtils jwtUtils;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 获取登录用户
        String token = request.getHeader("Authorization");
        //登录放行
        if ("/auth/login".equals(request.getRequestURI())) {
            doFilter(request, response, filterChain);
        }
        //没有token或者token为空字符串 返回401
        else if (ObjectUtils.isEmpty(token) || ObjectUtils.isNull(token)) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        }
        //解析token出错 返回401
        else {
//            try {
            //token解析(时间过期(报错ExpiredJwtException) 解析出错都会抛错)
            Claims claims = jwtUtils.parseToken(token);
            //解析数据放入sysUser
            SysUser sysUser = new SysUser();
            sysUser.setId(claims.get("id", Long.class));
            sysUser.setUsername(claims.get("username", String.class));
            sysUser.setNickname(claims.get("nickname", String.class));
            sysUser.setStatus(claims.get("status", Integer.class));
            sysUser.setAvatar(claims.get("avatar", String.class));
            //因为claims只接受ArrayList 所以要转换
            ArrayList roleList = claims.get("roleList", ArrayList.class);
            Set<SysRole> roleSet = new HashSet<>();
            roleSet.addAll(roleList);
            sysUser.setRoleList(roleSet);

            ArrayList<String> perms = claims.get("perms", ArrayList.class);
            Set<String> permsSet = new HashSet<>();
            permsSet.addAll(perms);
            sysUser.setPerms(permsSet);
            // 造用户信息（现在没放权限数据）
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(sysUser, null, sysUser.getAuthorities());
            //放入用户信息
            SecurityContextHolder.getContext().setAuthentication(authentication);
            // 放行
            doFilter(request, response, filterChain);
//            } catch (RuntimeException runtimeException) {
//                //401
//                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
//                //403
////                response.setStatus(HttpServletResponse.SC_FORBIDDEN);
//                return;
//            }
        }
    }
}
